﻿using System;
using System.Collections.Generic;
using Core.DataAccess.Model.Project.Queue;
using Core.Framework.Model.Common;
using Core.IBusiness.IUserModule;
using Quartz;
using System.Linq;
using System.Threading.Tasks;
using Core.Framework.Redis.Queue_Helper;
using Core.Framework.Util.Common;

namespace Core.ApiClient
{
    /// <summary>
    /// 清除过期的用户令牌
    /// </summary>
    public class ClearExpiredUserToken : ITimerJob
    {
        public void Execute(IJobExecutionContext jobContext)
        {
            List<ProjectModuleUser> source = new List<ProjectModuleUser>();

            using (var context = new ProjectSocketContext())
            {
                source =
                    context
                        .ProjectModuleUser
                        .Where(a => a.EndTime != null & a.EndTime < DateTime.Now)
                        .ToList();

                if (null != source && source.Count > 0)
                {
                    foreach (var item in source)
                    {
                        item.EndTime = null;
                    }

                    context.SaveChanges();
                }

            };


            if (null != source && source.Count > 0)
            {
                foreach (var item in source)
                {
                    // 删除 用户登陆信息
                    RedisQueueHelper.HashDelete(RedisQueueHelperParameter.ProjectSocketUserLogin,
                        item.ProjectToken + item.Token);

                    // 删除 上次 websocket 身份信息
                    RedisQueueHelper.HashDelete(RedisQueueHelperParameter.WebSocketByToken, item.Token);

                    // 删除 APi 调用令牌
                    RedisQueueHelper.HashDelete(RedisQueueHelperParameter.ApiClientByToken, item.Token);

                }
            }

        }
    }
}
